package com.yupi.yupicturebackend.async;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.yupi.yupicturebackend.api.baidu.imageUnderstand.ImageUnderstandingFacade;
import com.yupi.yupicturebackend.api.deepseek.DeepseekApi;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.mapper.PictureMapper;
import com.yupi.yupicturebackend.model.entity.Picture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

// 新增专门用于异步调用的Service
@Service
@Slf4j
public class AsyncPictureService {

    @Resource
    private ImageUnderstandingFacade imageUnderstandingFacade;
    @Resource
    private DeepseekApi deepseekApi;
    @Resource
    private PictureMapper pictureMapper;

    @Async // 确保注解在public方法
    public void asyncProcess(String url, String description, Long id) {
        // 将原有savePictureElements实现搬到这里
        // 参数校验（非空检查属于业务校验，直接抛业务异常）
        if (StrUtil.isBlank(url) || StrUtil.isBlank(description)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }

        try {
            // 1. 调用百度AI识别图片
            String content = imageUnderstandingFacade.analyzeImageAndGetDescription(url, description);

            // 2. 调用DeepSeek解析元素
            List<String> keywords = deepseekApi.parseImageSearchKeywords(content); // 注意这里应该是content而非description

            // 3. 保存到数据库等后续操作
            Picture picture = new Picture();
            picture.setId(id);
            picture.setElements(JSONUtil.toJsonStr(keywords));
            // 注意 前面已经进行了picture表的插入 这里是更新才对 不然继续插入 会报错的 我这里是报了url不能为空才反应过来
            int result = pictureMapper.updateById(picture);
            ThrowUtils.throwIf(result <= 0, ErrorCode.OPERATION_ERROR, "保存图片元素失败");
        } catch (IOException e) {
            // 记录原始异常（重要！方便排查问题）
            log.error("图片元素解析失败，url: {}, 原因: {}", url, e.getMessage(), e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片解析服务暂时不可用");
        } catch (Exception e) {
            // 兜底异常处理
            log.error("保存图片元素未知错误，url: {}", url, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }
}